package com.train.mgr.modules.biz.controller;

import com.alibaba.excel.EasyExcel;
import com.train.common.exception.BizException;
import com.train.common.model.PageResult;
import com.train.common.model.R;
import com.train.mgr.modules.biz.dto.request.UserExerciseReqDTO;
import com.train.mgr.modules.biz.dto.response.UserExerciseRespListDTO;
import com.train.mgr.modules.biz.service.ILessonUserExerciseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * 用户课时练习表 前端控制器
 * @author cxg
 * @date 2025-09-30
 */

@Slf4j
@RequiredArgsConstructor
@RestController
@Api( tags = "用户课时练习")
@RequestMapping("/lessonUserExercise")
public class LessonUserExerciseController {

    private final ILessonUserExerciseService lessonUserExerciseService;

    /**
     * 条件 分页查询 (仅作参考)
     * @author: cxg
     * @date: 2025-09-30
     */
    @GetMapping("/user_exercise_list")
    @ApiOperation("用户学习记录")
    public R<PageResult<UserExerciseRespListDTO>> userExerciseList(UserExerciseReqDTO params) {
        return R.succeed(lessonUserExerciseService.userExerciseList(params));
    }

    @GetMapping("/export_user_exercise")
    @ApiOperation("导出学习记录")
    public void excel(HttpServletResponse response,UserExerciseReqDTO params) throws Exception {
        params.setLimit(5000L);//最多导出5000条
        PageResult<UserExerciseRespListDTO> page = lessonUserExerciseService.userExerciseList(params);
        if(page == null || page.getList() == null || page.getList().size() ==0){
            throw new BizException("导出数据为空～");
        }
        //log.info("--------------------------- {}"+JSONObject.toJSONString(page.getList()));
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("学习记录文件", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
        EasyExcel.write(response.getOutputStream(), UserExerciseRespListDTO.class).sheet("学习记录").doWrite(page.getList());
    }

}
